<template>
  <div class="ht-container" v-loading="state.loading">
    <HtHeader :data="breadData">
      <div>
        <el-button
          style="margin-top:4px;"
          type="primary"
          @click="() => (state.exportVsible = true)"
          >导入酒罐</el-button
        >
      </div>
    </HtHeader>

    <div>
      <OldHtSearch
        @handelVisible="handelVisible"
        placeholder="搜索    酒罐名称、酒罐编号、酒品名称、酒品代码"
        @reset="reset"
        :showFilter="true"
        @search="search"
      >
        <el-col :span="8">
          <el-form-item label="所属部门">
            <ht-select-org
              :clearable="true"
              v-model="state.filter.manageOrganizationUnitId"
              @change="handleSearch"
            ></ht-select-org>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="存放酒库">
            <SelectWineInventory
              v-model="state.filter.warehouseCode"
              @change="handleSearch"
            ></SelectWineInventory>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="存放酒品">
            <SelectWine
              v-model="state.filter.breedCode"
              @change="handleSearch"
            ></SelectWine>
          </el-form-item>
        </el-col>
      </OldHtSearch>
      <el-card class="ht-card" style="margin-top: 16px">
        <ht-table
          class="ht-table-no-border"
          :data="state.dataSource"
          @onchange="changePage"
          style="width: 100%; margin-top: 12px"
          border
          @selection-change="(e) => (state.selectRows = e)"
          :checked="false"
          pageStyle="text-align:right"
          :height="`calc(100vh - 314px - ${state.searchHeight}px)`"
          highlight-current-row
          :page-info="{
            currentPage: state.filter.currentPage,
            pageSize: state.filter.maxResultCount,
            skipCount: state.filter.skipCount,
            totalCount: state.filter.totalCount,
          }"
          :columns="columns"
        >
          <Temp slot="empty">
            <span slot="tips">暂无数据哦</span>
          </Temp>

          <template slot="workGroup" slot-scope="{ row }">
            {{ row.workGroup || '--' }}
          </template>
          <template slot="warehouseName" slot-scope="{ row }">
            {{ row.warehouseName || '--' }}
          </template>
          <template slot="spaceName" slot-scope="{ row }">
            {{ row.spaceName || '--' }}
          </template>
          <template slot="wineBreedName" slot-scope="{ row }">
            {{ row.wineBreedName || '--' }}
          </template>
          <template slot="wineBreedCode" slot-scope="{ row }">
            {{ row.wineBreedCode || '--' }}
          </template>
          <template slot="wineBreedMaduDate" slot-scope="{ row }">
            {{ row.wineBreedMaduDate || '--' }}
          </template>
          <template slot="stewDays" slot-scope="{ row }">
            <span v-if="row.stewDays"> {{ row.stewDays + ' 天' }}</span>
            <span v-else>--</span>
          </template>
          <template slot="lastWineTemperature" slot-scope="{ row }">
            <span v-if="row.lastWineTemperature">
              {{ row.lastWineTemperature + ' ℃' }}</span
            >
            <span v-else>--</span>
          </template>
          <template slot="lastAlcoholicity" slot-scope="{ row }">
            <span v-if="row.lastAlcoholicity">
              {{ row.lastAlcoholicity + '  %vol' }}</span
            >
            <span v-else>--</span>
          </template>
          <template slot="weight" slot-scope="{ row }">
            <span v-if="row.weight"> {{ row.weight }}{{ row.uom }}</span>
            <span v-else>--</span>
          </template>
          <template slot="level" slot-scope="{ row }">
            <span v-if="row.level"> {{ row.level }}{{ row.uom }}</span>
            <span v-else>--</span>
          </template>

          <template slot="handel">
            <span class="cursor" @click="state.visible = true">出入罐明细</span>
          </template>
        </ht-table></el-card
      >
    </div>

    <ht-drawer
      class="ht-new-drawer"
      v-model="state.visible"
      title="出入罐明细"
      size="57%"
    >
      <Inventorydetails></Inventorydetails>

      <div slot="foot">
        <el-button
          :loading="state.loading"
          style="margin-left:14px;float: left"
          @click="state.visible = false"
          >取消</el-button
        >
      </div>
    </ht-drawer>
    <!-- 导入酒品弹框 -->
    <el-dialog
      :visible.sync="state.exportVsible"
      title=""
      v-if="state.exportVsible"
      :center="true"
      :show-close="false"
      :close-on-click-modal="false"
      width="428px"
    >
      <div
        slot="title"
        style="font-size: 18px; text-align: left; font-weight: bold"
      >
        导入酒库
      </div>
      <div style="font-size: 14px">
        请下载导入模板，按照模板录入酒罐信息后，进行导入酒罐
        <p style="color: var(--warning); padding: 0; margin-top:20px;">
          注意：导入新的酒罐信息会新增酒罐信息，导入已有的酒罐信息则对原酒罐信息进行更新
        </p>
      </div>
      <div
        slot="footer"
        style="height: 40px; box-sizing: border-box; display: flex;
    justify-content: right;
    "
      >
        <ht-export
          url="/alcohol-management/api/JarStatus/ExportJarStockTemplate"
          com-style="margin-left:28px;"
          :export-before="true"
          type="primary"
          size="large"
          :method="'get'"
          ><el-button type="primary" style="margin-right: 20px;"
            >下载模板</el-button
          ></ht-export
        >

        <el-upload
          class="upload-demo"
          :headers="{
            Authorization: 'Bearer' + ' ' + token,
          }"
          :http-request="handleAvatarSuccess"
          :on-error="onError"
          :show-file-list="false"
          :before-upload="beforeUpload"
          accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
          action="/alcohol-management/api/JarStatus/ImportJarStock"
        >
          <el-button type="primary" v-loading="state.loading"
            >导入酒罐</el-button
          >
        </el-upload>

        <div style="margin-left:20px;">
          <el-button @click="state.exportVsible = false">
            取 消
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<!-- <Status color="var(--primary)">已完成</Status> -->

<script lang="ts">
import { BreadType, Column, PageType } from 'htui-yllkbz/src/packages/type';
import { baseConfig, _axios } from 'vue-kst-auth';
import Temp from '@/components/temp.vue';
import { Component, Vue, Watch } from 'vue-property-decorator';
import SelectWine from '@/components/selectWine.vue';
import OldHtSearch from '@/components/oldHtSearch.vue';
import SelectWineInventory from '@/components/selectWineInventory.vue';
import Status from '@/components/status.vue';
import HtHeader from '@/components/htHeader.vue';
import Inventorydetails from './inventorydetails.vue';
import { JarStatusApi } from '@/plugins/api';

interface State {
  /** 数据状态 */
  exportVsible: boolean;
  loading: boolean;
  visible: boolean;
  searchHeight: number;
  activeName: string;
  testValue?: string;
  btnText: string;
  titleText: string;

  dataSource: any;
  /** 选中的数据 */
  selectRow: any;
  /** 批量选中的数据 */
  selectRows: any[];
  filter: {
    keyWords: string | undefined;
    manageOrganizationUnitId: string | undefined;
    warehouseCode: string | undefined;
    breedCode: string | undefined;
    sorting: string | undefined;
    skipCount: number;
    maxResultCount: number;
    totalCount: number;
    currentPage: number;
  };
}
@Component({
  components: {
    OldHtSearch,
    Temp,
    Status,
    HtHeader,
    Inventorydetails,
    SelectWine,
    SelectWineInventory,
  },
})
export default class Index extends Vue {
  JarStatusApi = new JarStatusApi('/alcohol-management', _axios);
  /** 数据 */
  state: State = {
    exportVsible: false,
    loading: false,

    activeName: 'third',
    testValue: undefined,
    searchHeight: 84,
    visible: false,
    dataSource: [],
    selectRows: [],
    selectRow: {},

    btnText: '',
    titleText: '',
    filter: {
      keyWords: undefined,
      manageOrganizationUnitId: undefined,
      warehouseCode: undefined,
      breedCode: undefined,
      skipCount: 0,
      sorting: 'product.creationTime desc',
      maxResultCount: 20,
      currentPage: 1,
      totalCount: 0,
    },
  };

  /** 生命周期 */
  mounted() {
    this.getDataSource();
    //this.$notify.success('测试能够更改文件');
  }

  /** 搜索框 */
  handelVisible(height: number) {
    this.state.searchHeight = height;
  }
  /** 重置 */
  reset() {
    const { filter } = this.state;
    filter.keyWords = '';

    filter.manageOrganizationUnitId = '';
    filter.breedCode = '';
    filter.warehouseCode = '';

    this.handleSearch();
  }
  /** 搜索的回调 */
  search(data: any) {
    this.state.filter.keyWords = data.keys;

    this.handleSearch();
  }
  /** 文件上传成功 */
  handleAvatarSuccess(data: any) {
    // this.state.loading = true;
    // eslint-disable-next-line  @typescript-eslint/no-this-alias
    const that = this;
    this.state.loading = true;
    const xhr = new XMLHttpRequest();
    const formData = new FormData();
    formData.append('file', data.file);
    xhr.open('post', data.action); //url填写后台的接口地址，如果是post，在formData append参数（参考原文地址）
    xhr.setRequestHeader('__tenant', baseConfig.getCookie('__tenant'));
    xhr.setRequestHeader(
      'Authorization',
      'Bearer ' + baseConfig.getCookie('Abp.AuthToken')
    );
    xhr.responseType = 'blob';
    xhr.onload = function(e) {
      const res: any = e.target;

      if (res.status == 204 || res.status == 200) {
        if (res.response && res.response.type == 'application/octet-stream') {
          const blob = res.response;
          /** 创建下载链接 */
          // const downloadHref =
          //   "/tai-zhang/api/asset-management/download-asset-template";
          const downloadHref = window.URL.createObjectURL(blob);
          /** 创建a标签并为其添加属性 */
          const downloadLink = document.createElement('a');
          downloadLink.href = downloadHref;
          downloadLink.download = `导入失败说明.xlsx`;
          /** 触发点击事件执行下载 */
          downloadLink.click();
          /** 下载完成进行释放 */

          window.URL.revokeObjectURL(downloadHref);
          that.$notify.error('导入失败！请查看下载文件说明。');
          that.state.loading = false;
          that.handleSearch();
        } else {
          that.$notify.success('导入成功！');
          that.state.exportVsible = false;
          that.handleSearch();
          that.state.loading = false;
        }
      } else {
        const blob = res.response;
        /** 创建下载链接 */
        // const downloadHref =
        //   "/tai-zhang/api/asset-management/download-asset-template";
        const downloadHref = window.URL.createObjectURL(blob);
        /** 创建a标签并为其添加属性 */
        const downloadLink = document.createElement('a');
        downloadLink.href = downloadHref;
        downloadLink.download = `导入失败说明.xlsx`;
        /** 触发点击事件执行下载 */
        downloadLink.click();
        /** 下载完成进行释放 */

        window.URL.revokeObjectURL(downloadHref);
        that.$notify.error('导入失败！请查看下载文件说明。');
        that.state.loading = false;
      }
    };
    xhr.send(formData);
  }
  /** 上传之前的文件严重 */
  beforeUpload(file: File) {
    if (file.name) {
      if (file.name.lastIndexOf('.xls') > -1) {
        return true;
      } else {
        this.$notify.error('请选择上传excel文件');
        return false;
      }
    } else {
      this.$notify.error('请选择上传excel文件');
      return false;
    }
  }
  onError() {
    this.$notify.error('上传失败,请稍后再试');
  }
  handleSearch() {
    this.state.filter.skipCount = 0;
    this.state.filter.currentPage = 1;

    this.getDataSource();
  }
  /** 查询列表 */
  getDataSource() {
    this.state.loading = true;
    const { filter } = this.state;

    this.JarStatusApi.getWinePageList(
      filter.keyWords,
      filter.manageOrganizationUnitId,
      filter.warehouseCode,
      filter.breedCode,
      filter.skipCount,
      filter.maxResultCount,
      undefined
    )
      .then((res: any) => {
        this.state.dataSource = res.items || [];

        this.state.filter.totalCount = res.totalCount || 0;
      })
      .finally(() => {
        this.state.loading = false;
      });
  }
  //添加酒品
  sumbit() {
    const data = (this.$refs.addWine as any).submit();
  }
  //编辑
  editData() {
    this.state.btnText = '保存';
    this.state.titleText = '编辑';
    this.state.visible = true;
  }
  //添加酒品

  addWine() {
    this.state.btnText = '添加';
    this.state.titleText = '添加';
    this.state.visible = true;
  }
  //分页
  changePage(data: PageType) {
    // const data = e.detail[0];
    this.state.filter.currentPage = data.currentPage;
    this.state.filter.maxResultCount = data.maxResultCount;
    this.state.filter.skipCount = data.skipCount;
    this.getDataSource();
  }

  /** 监听 */
  /** 计算属性 */
  /** 计算属性 */

  get columns(): Column[] {
    return [
      { key: 'sapName', title: '酒罐名称' },
      { key: 'sapCode', title: '酒罐编号' },

      { key: 'workGroup', title: '所属部门' },
      { key: 'warehouseName', title: '存放酒库' },
      { key: 'spaceName', title: '存放库位' },
      { key: 'wineBreedName', title: '酒品名称' },

      { key: 'wineBreedCode', title: '酒品代码' },
      { key: 'wineBreedMaduDate', title: '生产年月' },
      { key: 'stewDays', title: '已静置时间' },

      { key: 'weight', title: '原度数量' },
      { key: 'level', title: '当前液位' },
      { key: 'lastWineTemperature', title: '最近温度' },
      { key: 'lastAlcoholicity', title: '最近酒度' },
      // { key: "handel", title: "操作" },
    ];
  }

  get breadData(): BreadType[] {
    return [
      { key: 'k1', title: '库存业务管理' },
      { key: 'k2', title: '酒罐库存' },
    ];
  }
}
</script>
<style lang="scss" scoped>
.cursor {
  color: var(--primary);
  cursor: pointer;
}
:deep(.el-drawer__body > div) {
  padding: 0 !important;
}
</style>
